package com.h3c.nem.utils;

import com.alibaba.fastjson.JSONObject;
import com.h3c.nem.client.EosSyncDataClient;
import io.swagger.models.auth.In;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;

/**
 * EOS相关方法
 *
 * @author z22968
 * @date 2022/6/20 9:56
 */
@Slf4j
@Component
public class EosUtils {
    @Value("${eos.nem.account}")
    private String eosNemAccount;

    @Value("${eos.nem.password}")
    private String eosNemPassword;

    @Value("${eos.msg.token.url}")
    private String eosMsgTokenUrl;

    @Value("${eos.msg.send.url}")
    private String eosMsgSendUrl;

    @Resource
    EosSyncDataClient eosSyncDataClient;

    @Resource
    RestTemplate restTemplate;

    // token
    private static String token;

    // 过期时间
    private static long tokenExpireTime;

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class CommResponseBody {
        private Boolean flag;
        private Integer code;
        private String message;
    }

    /**
     * 获取eos token（原commService上的方法）
     *
     * @return java.lang.String
     * @author z22968
     * @date 2022-06-20 09:59
     */
    public String getEosMsgToken() {
        if (StringUtils.isEmpty(token) || tokenExpireTime < System.currentTimeMillis()) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("account", eosNemAccount);
            jsonObject.put("password", eosNemPassword);    //EOS上服务的账户和密码
            JSONObject eosToken = eosSyncDataClient.getEosToken(jsonObject.toJSONString());
            Integer code = (Integer) eosToken.get("code");
            if (code == 20220) {
                LinkedHashMap<String, Object> object = (LinkedHashMap) eosToken.get("data");
                token = (String) object.get("token");
                // 设置过期时间2小时
                tokenExpireTime = System.currentTimeMillis() + 2 * 60 * 60 * 1000;
            } else {
                throw new AppBusinessException("获取eosToken失败");
            }
        }
        return token;
    }

    /**
     * 通过eos消息中心发送邮件消息（原commService上的方法）
     *
     * @param sendTo  收件人邮箱，逗号分隔
     * @param copyTo  抄送人邮箱，逗号分隔
     * @param content 内容
     * @param title   标题
     * @return void
     * @author z22968
     * @date 2022-06-20 09:59
     */
    public void sendEosMail(String sendTo, String copyTo, String title, String content) {
        sendEosMail(sendTo, copyTo, title, content, null);
    }

    /**
     * 通过eos消息中心发送邮件消息（原commService上的方法）
     *
     * @param sendTo         收件人邮箱，逗号分隔
     * @param copyTo         抄送人邮箱，逗号分隔
     * @param content        内容
     * @param title          标题
     * @param attachFileList 附件
     * @return void
     * @author z22968
     * @date 2022-06-20 10:00
     */
    public void sendEosMail(String sendTo, String copyTo, String title, String content, List<File> attachFileList) {
        if (StringUtils.isEmpty(sendTo) || StringUtils.isEmpty(content)) {
            return;
        }
        String eosMsgToken = getEosMsgToken();
        JSONObject mailObject = new JSONObject();
        List<JSONObject> mailAddressList = new ArrayList<>();
        String[] sendToAddress = sendTo.split(",");
        Arrays.stream(sendToAddress).forEach(Address -> {
            JSONObject ToAddress = new JSONObject();
            ToAddress.put("mailAddress", Address);//收件人集合
            ToAddress.put("type", BusiEnumDefine.SEND_TO_ADDRESS);//0为收件人，1为抄送人，2为秘送人
            mailAddressList.add(ToAddress);
        });
        if (!StringUtils.isEmpty(copyTo)) {
            String[] copyToAddress = copyTo.split(",");
            Arrays.stream(copyToAddress).forEach(Address -> {
                JSONObject ToAddress = new JSONObject();
                ToAddress.put("mailAddress", Address);//收件人集合
                ToAddress.put("type", BusiEnumDefine.COPY_TO_ADDRESS);//0为收件人，1为抄送人，2为秘送人
                mailAddressList.add(ToAddress);
            });
        }
        mailObject.put("msgType", BusiEnumDefine.EOS_MAIL_MSG);
        mailObject.put("clientId", BusiEnumDefine.EOS_CLIENT_ID);
        mailObject.put("mailAddressList", mailAddressList);
        mailObject.put("title", title);
        mailObject.put("content", content);
        if (attachFileList != null && attachFileList.size() > 0) {
            Map<String, byte[]> attachFileMap = new HashMap<>();
            attachFileList.forEach(attachFile -> {
                attachFileMap.put(attachFile.getName(), CommonUtil.getBytesByFile(attachFile));
            });
            mailObject.put("attachments", attachFileMap);
        }
        mailObject.put("sendMail", "App.NewEmployee@h3c.com");

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.setBearerAuth(eosMsgToken);
        HttpEntity<JSONObject> reqEntity = new HttpEntity<>(mailObject, httpHeaders);

        ResponseEntity<CommResponseBody> resEntity = restTemplate.exchange(eosMsgSendUrl, HttpMethod.POST, reqEntity, CommResponseBody.class);
        CommResponseBody responseBody = resEntity.getBody();
        if (responseBody.getCode() != 1000) {
            throw new AppBusinessException("EOS邮件发送异常");
        }
    }

    /**
     * 通过eos消息中心发送企业微信图文消息
     *
     * @param adAccountList 域账号list
     * @param agentId       应用id
     * @param title         标题
     * @param description   描述
     * @param url           点击跳转地址
     * @param picUrl        图片地址
     * @return void
     * @author z22968
     * @date 2022-06-20 10:46
     */
    public void sendEosWeChatImageMsg(List<String> adAccountList, String agentId, String title, String description, String url, String picUrl) {
        JSONObject requestBody = new JSONObject();
        requestBody.put("msgType", BusiEnumDefine.EOS_WX_MSG);
        requestBody.put("clientId", BusiEnumDefine.EOS_CLIENT_ID);
        requestBody.put("qwMsgType", 2); // 1=文本消息 2=图文消息 3=卡片消息 此处填2
        requestBody.put("agentId", agentId);
        requestBody.put("adAccountList", adAccountList);
        requestBody.put("title", title);
        requestBody.put("description", description);
        requestBody.put("url", url);
        requestBody.put("picUrl", picUrl);

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.setBearerAuth(getEosMsgToken());
        HttpEntity<JSONObject> reqEntity = new HttpEntity<>(requestBody, httpHeaders);

        ResponseEntity<CommResponseBody> resEntity = restTemplate.exchange(eosMsgSendUrl, HttpMethod.POST, reqEntity, CommResponseBody.class);
        CommResponseBody responseBody = resEntity.getBody();
        if (responseBody.getCode() != 1000) {
            throw new AppBusinessException("EOS企业微信消息发送异常");
        }
    }
}
